package com.talent.jiwen.my;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.HomeFragment;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseFragment;
import com.talent.jiwen.home.AddProblemActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.CouponListResult;
import com.talent.jiwen.http.result.GroupInfoResult;
import com.talent.jiwen.model.GradeInfo;
import com.talent.jiwen.ui.widgets.ChooseGradeDialog;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

public class CouponListFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    private int startIndex = 1;
    private int useStatus = 0;
    private static final String PARAM_USE_STATUS = "param.use.status";
    private CommonAdapter<CouponListResult.Coupon> couponAdapter;
    private List<CouponListResult.Coupon> dataList = new ArrayList<>();

    private int idBindStatus = 0;////是否绑定身份证（0：未绑定 1：绑定）

    public static final String REFRESH_COUPON_LIST = "refresh.coupon.list";

    public static CouponListFragment newInstance(int status) {
        Bundle args = new Bundle();
        args.putInt(PARAM_USE_STATUS, status);
        CouponListFragment couponListFragment = new CouponListFragment();
        couponListFragment.setArguments(args);
        return couponListFragment;
    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_COUPON_LIST)){
            refreshLayout.autoRefresh();
        }
    }


    @Override
    protected void initData() {

        registEventBus();
        useStatus = getArguments().getInt(PARAM_USE_STATUS);
        noDataIv.setImageResource(R.mipmap.img_no_coupon);

        initRecycleView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_coupon_no_use;
    }

    /**初始化recycleView
     *
     */
    private void initRecycleView(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        couponAdapter = new CommonAdapter<CouponListResult.Coupon>(getActivity(), R.layout.item_coupon_no_use, dataList) {
            @Override
            protected void convert(ViewHolder holder, final CouponListResult.Coupon coupon, int position) {
                RelativeLayout rootLayout = holder.getView(R.id.rootLayout);
                TextView moneyTv = holder.getView(R.id.moneyTv);
                TextView desTv = holder.getView(R.id.desTv);
                TextView couponNameTv = holder.getView(R.id.couponNameTv);
                TextView useTimeTv = holder.getView(R.id.useTimeTv);
                TextView optionTv = holder.getView(R.id.optionTv);
                ImageView flagIv = holder.getView(R.id.flagIv);

                moneyTv.setText("¥" + coupon.getDiscountAmount());
                desTv.setText(coupon.getDiscountName());
                couponNameTv.setText(coupon.getCouponName());

                long startTime = coupon.getCreateTime();
                long endTime = coupon.getCreateTime() + coupon.getValidTime() * 24 * 60 *60 *1000;
                useTimeTv.setText("(" + ms2DateWithPoint(startTime) + "-" + ms2DateWithPoint(endTime) + ")");

                switch (useStatus){
                    case 0:
                        //未使用
                        rootLayout.setBackgroundResource(R.mipmap.bg_coupon_normal);
                        optionTv.setText("立即体验");
                        optionTv.setVisibility(View.VISIBLE);
                        flagIv.setVisibility(View.GONE);

                        rootLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (idBindStatus == 0){
                                    intentActivity(CardBindActivity.class);
                                }else{
                                    if (SPUtil.intOut(SPConstant.SELECT_GRADE) == 0){
                                        ChooseGradeDialog gradeDialog=new ChooseGradeDialog(getActivity() ,new ChooseGradeDialog.OnTagClickListener() {
                                            @Override
                                            public void onClick(Dialog dialog, GradeInfo gradeInfo) {
                                                //保存选中的年级ID
                                                SPUtil.intIn(SPConstant.SELECT_GRADE , gradeInfo.getGradeId());
                                                EventBus.getDefault().post(HomeFragment.REFRESH_SELECT_GRADE);
                                                createGroupInfo(coupon);
                                            }
                                        } , true);
                                        gradeDialog.show();
                                    }else{
                                        //发起提问
                                        createGroupInfo(coupon);
                                    }
                                }
                            }
                        });
                        break;
                    case 1:
                        //已使用
                        rootLayout.setBackgroundResource(R.mipmap.bg_coupon_gray);
                        optionTv.setVisibility(View.GONE);
                        flagIv.setVisibility(View.VISIBLE);
                        flagIv.setImageResource(R.mipmap.iv_coupon_used);
                        break;
                    case 2:
                        //已过期
                        rootLayout.setBackgroundResource(R.mipmap.bg_coupon_gray);
                        optionTv.setVisibility(View.GONE);
                        flagIv.setVisibility(View.VISIBLE);
                        flagIv.setImageResource(R.mipmap.iv_coupon_out_time);

                        break;
                }
            }
        };
        recyclerView.setAdapter(couponAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                startIndex = 1;
                getCouponList();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                startIndex ++ ;
                getCouponList();
            }
        });

        refreshLayout.autoRefresh();
    }

    /**
     * 获取优惠券列表
     */
    private void getCouponList() {
        Map<String, String> map = new HashMap<>();
        map.put("useStatus", useStatus + "");
        map.put("startIndex", startIndex + "");

        Observable observable = ApiFactory.getEducationApiSingleton().getCouponList(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<CouponListResult>(getActivity()) {
            @Override
            protected void _onNext(CouponListResult result) {
                idBindStatus = result.getIDNoBindStatus();
                if(startIndex == 1){
                    dataList.clear();
                    dataList.addAll(result.getCouponList());
                    couponAdapter.notifyDataSetChanged();
                    refreshLayout.finishRefresh();
                }else{
                    dataList.addAll(result.getCouponList());
                    couponAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();

                    if (result.getCouponList().size() < 10){
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }

                if (Validators.isEmpty(dataList)){
                    if(noDataIv!=null){
                        noDataIv.setVisibility(View.VISIBLE);
                    }

                }else{
                    if(noDataIv!=null){
                        noDataIv.setVisibility(View.GONE);
                    }
                }

            }

            @Override
            protected void _onError(String message) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                }
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
    }

    /**时间转换
     *
     * @param _ms
     * @return
     */
    private static String ms2DateWithPoint(long _ms){
        Date date = new Date(_ms);
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
        return format.format(date);
    }

    /**进入发起提问之前先创建群组
     *
     */
    private void createGroupInfo(final CouponListResult.Coupon coupon){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().createGroupInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<GroupInfoResult>(getActivity()) {
            @Override
            protected void _onNext(GroupInfoResult groupInfoResult) {
                String groupId = groupInfoResult.getGroupId();
                boolean hasOrderNow = false;
                if (groupInfoResult.getExistImmediateStatus() == 0){
                    hasOrderNow = false;
                }else{
                    hasOrderNow = true;
                }
                AddProblemActivity.startAddProblemActivity(getActivity() , groupId , groupInfoResult.getAvailableCouponCount() , hasOrderNow
                        , JSON.toJSONString(coupon) ,"");
                getActivity().finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }
}
